package main

import (
	"flag"
	"net/http"
	"os"

	"gitee.com/dinglz/dingapi/dinglog"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/securecookie"
	"github.com/gorilla/sessions"
	"github.com/robfig/cron/v3"
)

var (
	version   string = "0.1 beta"
	port      *string
	path      string
	LookTimes int = 0
	store     *sessions.FilesystemStore
)

func init() {
	port = flag.String("port", "80", "启动端口")
	flag.Parse()
	path, _ = os.Getwd()
	_, err := os.Stat(path + "\\sesskey")
	if err != nil {
		os.Mkdir(path+"\\sesskey", 0666)
	}
}

func WriteUpLookTimes() gin.HandlerFunc {
	return func(c *gin.Context) {
		LookTimes++
	}
}

func main() {
	store = sessions.NewFilesystemStore("./sesskey", securecookie.GenerateRandomKey(32), securecookie.GenerateRandomKey(32))
	timeupdater := cron.New()
	timeupdater.AddFunc("@daily", func() {
		dinglog.Debug("每日，清空访问次数统计")
	})
	dinglog.Info("正在初始化服务器路由...")
	path, _ = os.Getwd()
	gin.SetMode(gin.ReleaseMode)
	server := gin.Default()
	server.Use(WriteUpLookTimes())
	apir := server.Group("/api")
	{
		apir.GET("/version", func(c *gin.Context) {
			c.String(http.StatusOK, version)
		})
		apir.GET("/logo", func(c *gin.Context) {
			c.File(path + "\\image\\dingdoc.png")
		})
		apir.GET("/looktimes", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{"times": LookTimes})
		})
		apir.GET("/set", func(c *gin.Context) {
			session, _ := store.Get(c.Request, "test")
			session.Values["text"] = c.DefaultQuery("test", "默认")
			session.Save(c.Request, c.Writer)
			c.JSON(200, gin.H{"status": "ok"})
		})
		apir.GET("/get", func(c *gin.Context) {
			session, _ := store.Get(c.Request, "test")
			c.JSON(200, gin.H{"text": session.Values["text"]})
		})
	}
	server.NoRoute(func(c *gin.Context) {
		c.JSON(http.StatusNotFound, gin.H{"status": 404, "msg": "未找到路由"})
	})
	dinglog.Info("正在启动服务器...")
	err := server.Run(":" + *port)
	if err != nil {
		dinglog.Error("服务器启动失败，失败原因:" + err.Error())
	}
}
